<template>
	<page-meta :page-style="'overflow:' + (show ? 'hidden' : 'visible')"></page-meta>
	<view class="complaint">
		<view class="publishDemand-content">
			<!-- 订单编号 -->
			<view class="formLabel uni-flex uni-align-center uni-justify-between border-bottom">
				<text class="label">订单编号</text>
				<view class="uni-flex-item uni-flex uni-justify-end uni-align-center">
					{{ info.orderId }}
				</view>
			</view>
			<!-- 投诉原因（核心显示区域） -->
			<view class="formLabel uni-flex uni-align-center uni-justify-between border-bottom">
				<text class="label">投诉原因</text>
				<view class="uni-flex-item uni-flex uni-justify-end uni-align-center right-box" @click="toSelect">
					<!-- 修复：确保selectedReason是响应式数据 -->
					<text class="text1" v-if="selectedReason">{{ selectedReason }}</text>
					<text class="placeholder" v-else>请选择您遇到的问题</text>
					<uni-icons type="right" size="15" color="#999999"></uni-icons>
				</view>
			</view>
			<!-- 联系电话 -->
			<view class="formLabel uni-flex uni-justify-between border-bottom bankCode">
				<text class="label">联系电话</text>
				<view class="uni-flex-item uni-flex uni-align-center">
					<!-- 修复：v-model绑定到正确的联系电话字段（原绑定bankNumber错误） -->
					<uni-easyinput :inputBorder="false" v-model="info.userPhone" placeholderStyle="font-size:28rpx"
						:clearable="false" placeholder="请输入您的联系方式,便于平台与您联系"></uni-easyinput>
				</view>
			</view>
			<!-- 补充描述 -->
			<view class="formLabel uni-flex uni-justify-between bankCode">
				<text class="label">补充描述</text>

				<view class="textarea-wrapper">
					<uni-easyinput type="textarea" v-model="info.content" maxlength="500" placeholder="请输入"
						placeholderStyle='font-size:28rpx;' />
					<view class="counter">{{ info.content.length }}/500</view>
				</view>
			</view>
			<!-- 图片凭证 -->
			<view class="formLabel uni-flex uni-justify-between bankCode">
				<text class="label">图片凭证</text>
				<view class="uni-flex-item uni-flex uni-align-center">
					<uni-file-picker limit="9" mode="grid" :del-icon="true" file-mediatype="image"
						:imageStyles="imageStyles" @success="handleFileSuccess" @fail="handleFileFail"
						@select="handleFileSelect">
						<view class="custom-upload">
							<uni-icons type="camera" size="26"></uni-icons>
							<text class="text">添加图片</text>
						</view>
					</uni-file-picker>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="button-group">
			<button type="default" class="submit" @click="submitComplaint">提交</button>
		</view>

		<!-- 投诉原因选择弹窗 -->
		<uni-popup ref="alertDialog" type="bottom" style="height: 400rpx; overflow-y: auto">
			<view class="uni-flex uni-justify-between uni-align-center top">
				<text @click="cancelSelect">取消</text>
				<text @click="confirmSelection" style="color: #2F80ED;">确定</text>
			</view>
			<uni-transition ref="ani" custom-class="transition" :mode-class="['fade', 'zoom-in']" :show="true">
				<uni-list>
					<uni-list-item clickable v-for="(item, index) in reportCategoryList" :key="item.value"
						:title="item.label" :showArrow="false" :class="{ 'selected': selectedIndex === index }"
						@click="selectItem(index)" />
				</uni-list>
			</uni-transition>
		</uni-popup>
		<uni-popup ref="successPopup" type="center" custom-style="width: 600rpx; padding: 40rpx;">
			<view class="success-popup">
				<!-- 对勾图标 -->

				<image :src="`${$ImgBaseUrl}order-report.png`" mode="widthFix" class="success-icon" />
				<text class="success-title">您的投诉已提交</text>
				<text class="success-desc">平台售后人员将尽快与您联系</text>
				<button class="success-btn" @click="closeSuccessPopup">知道了</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance,

	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		qiNiuFileUpload
	} from "@/utils/qiniu.js"; // 七牛云上传工具

	import {
		reportCategory,
		addReport
	} from '@/api/report.js'; // 获取投诉原因列表接口

	// 1. 修复：响应式数据初始化（原imageValue未定义）
	const reportCategoryList = ref([]); // 投诉原因列表
	const selectedIndex = ref(-1); // 选中项索引（-1表示未选中）
	const selectedReason = ref(''); // 选中的投诉原因文本（核心显示数据）
	const alertDialog = ref(null); // 弹窗引用
	const show = ref(false); // 控制页面滚动锁定
	const imageValue = ref([]); // 图片凭证列表（修复：新增响应式数据存储图片路径）
	const successPopup = ref(null); // 提交成功弹窗的引用
	const submitData = ref({}); // 新增全局变量
	const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel(); // 页面通信通道

	// 图片样式配置
	const imageStyles = {
		width: 64,
		height: 64,
		border: {
			width: 1,
			style: "dashed",
			color: "#CFCFCF",
			radius: 4
		}
	};

	// 2. 选择投诉原因项
	const selectItem = (index) => {
		selectedIndex.value = index;
		const selectedItem = reportCategoryList.value[index];
		selectedReason.value = selectedItem?.label || '';
		info.categoryId = selectedItem?.id || ''; // 正确：用item.id赋值categoryId
	};

	// 3. 图片选择相关方法（修复：原方法命名冲突+imageValue未定义）
	const handleFileSelect = (e) => {
		console.log("图片选择事件：", e);
		// 存储临时图片路径（uni-file-picker的select事件返回tempFilePaths）
		imageValue.value = e.tempFilePaths || [];
	};
	const handleFileSuccess = (e) => {
		console.log("图片上传成功：", e);
		// 若需要手动处理上传结果，可在此补充逻辑
	};
	const handleFileFail = (e) => {
		console.error("图片选择/上传失败：", e);
		uniShowToast({
			title: "图片操作失败",
			icon: "error"
		});
	};
	// 打开成功弹窗
	const openSuccessPopup = () => {
		successPopup.value?.open();
	};

	// 关闭成功弹窗（同时返回上一页等逻辑）
	const closeSuccessPopup = () => {
		successPopup.value?.close();
		// 访问全局submitData的value
		eventChannel.emit && eventChannel.emit("acceptDataInvoicing", submitData.value);
		setTimeout(() => uni.navigateBack(), 300);
	};
	// 4. 七牛云图片上传（优化：增加参数校验）
	const uploadAvatarToQiNiu = async () => {
		// 若没有选择图片，直接返回空数组
		if (imageValue.value.length === 0) return [];

		let files = imageValue.value.map((item) => ({
			path: item,
			// 优化：用订单号+时间戳+随机数确保图片路径唯一
			key: `complaint/images/${info.orderId}/${Date.now()}_${Math.floor(Math.random() * 1000)}.png`
		}));

		return new Promise((resolve, reject) => {
			qiNiuFileUpload(
				files,
				(successUrl) => {
					console.log("七牛云上传成功，图片URL：", successUrl);
					resolve(successUrl);
				},
				(error) => {
					console.error("七牛云上传失败：", error);
					reject(new Error("图片上传失败，请重试"));
				}
			);
		});
	};

	// 5. 打开投诉原因选择弹窗
	const toSelect = () => {
		show.value = true; // 锁定页面滚动
		alertDialog.value?.open(); // 打开弹窗（?.防止未获取到弹窗引用报错）
	};

	// 确认选择
	const confirmSelection = () => {
		if (selectedIndex.value >= 0 && reportCategoryList.value.length > 0) {
			const selectedItem = reportCategoryList.value[selectedIndex.value];
			if (selectedItem) {
				selectedReason.value = selectedItem.label;
				info.complaintReason = selectedItem.id || selectedItem
					.label; // 可选：若接口需要complaintReason存id，改为id；若存文本则保留label
				info.categoryId = selectedItem.id; // 正确：用item.id赋值categoryId
			}
		} else {
			selectedReason.value = '';
			info.complaintReason = '';
			info.categoryId = '';
		}
		alertDialog.value?.close();
		show.value = false;
	};

	// 7. 取消选择投诉原因
	const cancelSelect = () => {
		alertDialog.value?.close();
		show.value = false;
	};

	// 8. 表单核心数据（修复：联系电话字段绑定错误）
	const info = reactive({
		categoryId: "",
		type: "ORDER",
		reportId: "",
		content: "",
		img: "",
		title: "",
		userPhone: "",
		orderId: "", // 接收订单编号的临时字段
	});

	// 9. 获取投诉原因列表（优化：增加错误提示）
	const getReportCategory = async () => {
		try {
			const res = await reportCategory();
			if (res?.code === 200 && Array.isArray(res.data)) {
				reportCategoryList.value = res.data;
				console.log("获取投诉原因列表成功：", reportCategoryList.value);
			} else {
				throw new Error("投诉原因列表格式错误");
			}
		} catch (error) {
			console.error("获取投诉原因列表失败：", error);
			uniShowToast({
				title: "加载投诉原因失败",
				icon: "error"
			});
		}
	};

	// 10. 提交投诉表单（修复：增加数据校验+图片上传逻辑）
	const submitComplaint = async () => {
		// 校验reportId（订单编号）
		if (!info.orderId) {
			return uni.showToast({
				title: '订单编号异常，请重新进入',
				icon: 'none'
			});
		}
		// 校验categoryId（投诉原因id）
		if (!info.categoryId) {
			return uni.showToast({
				title: '请选择投诉原因',
				icon: 'none'
			});
		}
		// 校验联系电话
		if (!info.userPhone) {
			return uni.showToast({
				title: '请输入联系电话',
				icon: 'none'
			});
		}
		// 图片凭证
		if (imageValue.value.length === 0) {
			return uni.showToast({ // 提示用户选择图片
				title: '请上传图片凭证',
				icon: 'none', // 不显示默认图标，仅文字提示
				duration: 1500 // 提示时长1.5秒
			});
		}

		try {
			// 图片上传
			const imageUrls = await uploadAvatarToQiNiu();
			const {
				complaintReason,
				...restInfo
			} = info;
			submitData.value = {
				...restInfo,
				img: imageUrls
			};
			// 调用提交接口
			const response = await addReport(submitData.value);
			if (response?.code === 200) {
				openSuccessPopup();
			} else {
				throw new Error(response?.message || "提交失败，请重试");
			}
		} catch (error) {
			console.error("投诉提交失败：", error);
			uni.showToast({
				title: error.message,
				icon: 'none'
			});
		}
	};

	// 11. 页面加载时接收参数并初始化数据
	onLoad((option) => {
		if (option.id) {
			info.orderId = option.id;
		}
		// if (option.paymentAmount) info.invoiceAmount = option.paymentAmount;
		getReportCategory();
	});
</script>

<style scoped lang="scss">
	.complaint {
		padding: 26rpx 24rpx 81rpx;
		background: #f5f5f5;
		min-height: calc(100vh - 26rpx);

		.publishDemand-content {
			background: #ffffff;
			border-radius: 20rpx;
			padding: 0 26rpx 40rpx 23rpx;

			.border-bottom {
				border-bottom: 1px solid #e2e2e2;
			}

			.right-box {}

			.formLabel {
				padding: 24rpx 0;

				.slectBank {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;

					.price {
						color: #ff6a47;
					}
				}

				.label {
					flex: 0 0 145rpx;
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 70rpx;
				}
			}

			.custom-upload {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				width: 115rpx;
				height: 115rpx;
				border-radius: 10rpx;
				border: 1rpx dashed #cfcfcf;

				.text {
					font-weight: 400;
					font-size: 22rpx;
					color: #999999;
				}
			}
		}

		.button-group {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 136rpx;
			padding-top: 20rpx;
			background: #ffffff;

			.submit {
				width: 93%;
				height: 80rpx;
				background: #2f80ed;
				border-radius: 44rpx;
				color: #fff;
				font-size: 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.top {
		padding: 0 30rpx;
		background: #fff;

		text {
			width: 90rpx;
			height: 80rpx;
			line-height: 80rpx;
			color: #3b4144;
			font-size: 30rpx;
		}
	}

	::v-deep .uni-easyinput {
		// width: 430rpx !important;
	}

	.placeholder {
		color: #999;
		font-size: 28rpx;
	}

	.textarea-wrapper {
		position: relative;
		width: 100%;
	}

	.counter {
		position: absolute;
		right: 20rpx;
		bottom: 10rpx;
		text-align: right;
		font-size: 12px;
		color: #999;
		pointer-events: none;
	}

	.success-popup {
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
		padding: 60rpx 100rpx;
		background-color: #fff;
		border-radius: 20rpx;

		.success-icon {
			width: 116rpx;
			height: 116rpx;
			margin-bottom: 20rpx;
		}

		.success-title {
			font-size: 36rpx;
			font-weight: 500;
			color: #303133;
			margin-bottom: 10rpx;
		}

		.success-desc {
			font-size: 28rpx;
			color: #999;
			margin-bottom: 40rpx;
		}

		.success-btn {
			width: 100%;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 28rpx;
			border: 1rpx solid #2F80ED;
			color: #2F80ED;
			border-radius: 34rpx;
		}
	}
</style>